#include "stdafx.h"
#include "profilermanager.h"
#include "profiler.h"
#include "specprivate.h"

ProfilerManager::ProfilerManager( QWidget *parent /*= 0*/ )
	: QWidget(parent)
	, name("profiler")
	, profiler(new Profiler)
	, tableWidget(new QTableWidget)
{

}

ProfilerManager::~ProfilerManager()
{
	if (profiler)
	{
		QString file = Profiler::getProfilerFile();
		profiler->save(file);
		delete profiler;
		profiler = NULL;
	}
}

void ProfilerManager::initialize()
{
	QVBoxLayout* layout = new QVBoxLayout;
	layout->addWidget(tableWidget);
	setLayout(layout);

	if (loadProfiler()) 
	{
		QList<SpecPrivate*>& list = profiler->getSpec();
		int nCount = list.count();

		tableWidget->setRowCount(nCount);
		tableWidget->setColumnCount(1);
		tableWidget->setColumnWidth(0,QWidget::size().width()); 
		tableWidget->horizontalHeader()->setVisible(false);

		for (int i = 0; i < nCount; ++i)
		{
			SpecPrivate* spec = list.at(i);
			if (spec)
			{
				QTableWidgetItem *checkBox = new QTableWidgetItem(spec->name);
				Qt::CheckState state = spec->enable ? Qt::Checked : Qt::Unchecked;
				checkBox->setCheckState(state);

				QVariant v;
				v.setValue(spec);
				checkBox->setData(Qt::UserRole, v);
				tableWidget ->setItem(i, 0, checkBox);
			}
		}

		connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(cellChanged(int, int)));
	}
}

QString ProfilerManager::getName()
{
	return name;
}

QWidget* ProfilerManager::getUi()
{
	return this;
}

bool ProfilerManager::loadProfiler()
{
	if (profiler) 
	{
		QString file = Profiler::getProfilerFile();
		profiler->read(file);

		QDir dir(qApp->applicationDirPath());
		if (dir.cd("plugins")) 
		{
			QStringList filters;
			filters << "*.Dll" << "*.dll" << "*.DLL";
			QFileInfoList entries = dir.entryInfoList(filters);
			foreach (const QFileInfo &file, entries) 
			{
				const QString lowerFile = file.absoluteFilePath().toLower();
				if (!profiler->isExist(lowerFile))
				{
					SpecPrivate* spec = new SpecPrivate;
					spec->name = lowerFile;
					spec->enable = true;
					profiler->add(spec);
				}
			}
		}

		return true;
	}

	return false;
}

void ProfilerManager::cellChanged( int row, int column )
{
	QTableWidgetItem *checkBox = tableWidget->item(row, column);
	Qt::CheckState state = checkBox->checkState();
	QVariant v = checkBox->data(Qt::UserRole);
	SpecPrivate* spec = v.value<SpecPrivate*>();
	if (spec)
	{
		spec->name = checkBox->text();
		spec->enable = (state == Qt::Checked);
	}
}

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    Q_EXPORT_PLUGIN2(ProfilerManager, ProfilerManager);
#endif
